<?php
declare(strict_types=1);

namespace App\Controller\Chat;

use App\Common\Lib\Show;
use Orhanerday\OpenAi\OpenAi;

class ChatController
{
    public function chat()
    {
        $open_ai = new OpenAi(env('CHAT_GPT_API'));
//        echo $open_ai->listModels();
//        var_dump($open_ai->getCURLInfo());
        $complete = $open_ai->chat([
            'model' => 'gpt-3.5-turbo',
            'messages' => [
                [
                    "role" => "system",
                    "content" => "You are a helpful assistant."
                ],
                [
                    "role" => "user",
                    "content" => "Who won the world series in 2020?"
                ],
                [
                    "role" => "assistant",
                    "content" => "The Los Angeles Dodgers won the World Series in 2020."
                ],
                [
                    "role" => "user",
                    "content" => "Where was it played?"
                ],
            ],
            'temperature' => 1.0,
            'max_tokens' => 4000,
            'frequency_penalty' => 0,
            'presence_penalty' => 0,
        ]);
        $res = Show::json_decode($complete);
        var_dump($res);
        $complete = $open_ai->completion([
            'model' => 'text-davinci-002',
            'prompt' => 'Hello',
            'temperature' => 0.9,
            'max_tokens' => 150,
            'frequency_penalty' => 0,
            'presence_penalty' => 0.6,
        ]);
        var_dump($complete);
    }

    /**
     * 解析 Chat 响应
     */
    private function parseChatResponse($response)
    {
        $responseData = json_decode($response, true);
        $answer = $responseData['choices'][0]['message']['content'];
        return $answer;
    }

    /**
     * 创建 Chat 请求
     */
    private function createChatRequest($data)
    {
        return [
            'headers' => [
                'Content-Type' => 'application/json',
                'Authorization' => 'Bearer ' . env('CHAT_GPT_API'), // 替换为你的 API 密钥
            ],
            'body' => json_encode($data),
        ];
    }
}
